﻿using Autofac;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Office.Core;
using NLog;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wittur.GenereateKongCoCPDF.Core.Common;

namespace Wittur.GenereateKongCoCPDF.Core
{
    public class SampleSchedule
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 注册窗口
        /// </summary>
        private IContainer Container;

        public SampleSchedule(IContainer container)
        {
            Container = container;
        }

        public async Task Start()
        {
            Console.WriteLine("SampleSchedule Started!");
            logger.Info("SampleSchedule Started!");

            await AddMyJob1Async();
        }

        public async Task AddMyJob1Async()
        {
            var job = JobBuilder.Create<TestGenPDF>().Build();

            // 定义 Cron 表达式，例如：每天上午10: 15执行
            string cronExpression = ConfigHelper.Instance.GetString("RunCorn", "GenKongCoCPDF");//"0 15 10 * * ?";

            var trigger = TriggerBuilder.Create()
                .WithIdentity("GTrigger", "GGroup")
                .StartNow()
                .WithCronSchedule(cronExpression)
                .Build();
                
                //.WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForever(2)).Build();
            var cts = new CancellationTokenSource();

            var scheduler = await Container.Resolve<ISchedulerFactory>().GetScheduler();
            await scheduler.ScheduleJob(job, trigger, cts.Token);

            await scheduler.Start().ConfigureAwait(true);

            //Console.WriteLine("======================");
            //Console.WriteLine("Press Enter to exit...");
            //Console.WriteLine("======================");
            //Console.ReadLine();

            //cts.Cancel();
            //await scheduler.Shutdown().ConfigureAwait(true);
        }

        public void Stop()
        {
            Console.WriteLine("SampleSchedule Stoped!");
            logger.Info("SampleSchedule Stoped!");
        }
    }
}